
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.CharBuffer;
import java.rmi.Naming;

/*
 * NoteBoardClientGUI.java
 *
 * Created on November 21, 2009, 1:06 PM
 */
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;




/**
 *
 * @author  tomek
 */
public class NoteBoardClientGUI extends javax.swing.JFrame {
    NoteBoard nb; 
    CharBuffer cb = CharBuffer.allocate(256);
    int buffIndex = 0;
    private String currentPath = "/" ;
    static ClientCallback cc ;
    
    /** Creates new form NoteBoardClientGUI */
    public NoteBoardClientGUI() {
        initComponents();
        try {
            nb = (NoteBoard) Naming.lookup( "rmi://127.0.0.1:10888/note" );
            cc = new ClientCallbackImpl(this) ;
            UnicastRemoteObject.exportObject(cc, 0) ;
            Naming.rebind("rmi://127.0.0.1:10889/cc", cc) ;
            nb.registerForCallback(cc) ;
        } catch (NotBoundException ex) {
            Logger.getLogger(NoteBoardClientGUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MalformedURLException ex) {
            Logger.getLogger(NoteBoardClientGUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RemoteException ex) {
            Logger.getLogger(NoteBoardClientGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        this.doLs();
      
        
    }

    private void doCd(String path) {
        try {
            currentPath = nb.changeDir(path, currentPath);
            doLs();
        } catch (RemoteException ex) {
            Logger.getLogger(NoteBoardClientGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void doLs() {
        try {
            this.fileList.removeAll();
            Object[] files = nb.getFileList(currentPath);
            for (Object file : files)
            {
                this.fileList.add((String)file);
            }
        } catch (RemoteException ex) {
            Logger.getLogger(NoteBoardClientGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void getFile(String fileName) {
        FileWriter fstream = null;
        try {
            File f;
            f = new File(fileName);
            if (!f.exists()) {
                f.createNewFile();
            }
            fstream = new FileWriter(f);
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
            byte[] readContent = nb.getFile(fileName, currentPath);
            
            if (readContent != null)
                out.write(readContent); 
            
            out.close();
            
        } catch (IOException ex) {
            Logger.getLogger(NoteBoardClientGUI.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fstream.close();
            } catch (IOException ex) {
                Logger.getLogger(NoteBoardClientGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
   
        private void sendFile(String filePath) {
            BufferedInputStream bis = null;
            try
            {
            File f;
            f = new File(filePath);
            if (!f.exists()) 
            {
                return;
            }
            bis = new BufferedInputStream(new FileInputStream(f));
            final byte[] bytes = new byte[(int) f.length()];
            bis.read(bytes); 
            bis.close();
            
            String[] tmpFileNameSplit = filePath.split("/");
            String destFileName = tmpFileNameSplit[tmpFileNameSplit.length - 1];
            
            nb.sendFile(bytes, destFileName, currentPath);
        } catch (IOException ex) {
            Logger.getLogger(NoteBoardImpl.class.getName()).log(Level.SEVERE, null, ex);
            
        } finally {
            try {
                bis.close(); 
            } catch (IOException ex) {
                Logger.getLogger(NoteBoardImpl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
            
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        downloadBtn = new javax.swing.JButton();
        uploadBtn = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        cmdTextArea = new javax.swing.JTextArea();
        fileList = new java.awt.List();

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        downloadBtn.setText("Download");
        downloadBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                downloadBtnMouseClicked(evt);
            }
        });
        downloadBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                downloadBtnActionPerformed(evt);
            }
        });

        uploadBtn.setText("Upload");
        uploadBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                uploadBtnMouseClicked(evt);
            }
        });

        cmdTextArea.setColumns(20);
        cmdTextArea.setRows(5);
        cmdTextArea.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                cmdTextAreaFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                cmdTextAreaFocusLost(evt);
            }
        });
        cmdTextArea.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                cmdTextAreaKeyTyped(evt);
            }
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cmdTextAreaKeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(cmdTextArea);

        fileList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                fileListMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 633, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(downloadBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(uploadBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(379, 379, 379))
            .addComponent(fileList, javax.swing.GroupLayout.DEFAULT_SIZE, 633, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(uploadBtn)
                    .addComponent(downloadBtn))
                .addGap(18, 18, 18)
                .addComponent(fileList, javax.swing.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void cmdTextAreaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cmdTextAreaKeyPressed
 if (evt.getKeyCode() == KeyEvent.VK_BACK_SPACE)
 {
     buffIndex--;
     return;
 }
        
    
    cb.put(buffIndex++, evt.getKeyChar());     
    if (evt.getKeyChar() == '\n')
    {   
        String command = "";
        int index = 0;
        while (cb.get(index) != '\n')
        {
            command += String.valueOf(cb.get(index));
            index++;
        }
        
        command.trim();
        String[] splitCommand = command.split(" ");
        
        if (splitCommand[0].equals("ls"))
                doLs();  
        else if (splitCommand[0].equals("cd"))
            doCd(splitCommand[1]);
        else if (splitCommand[0].equals("get"))
            getFile(splitCommand[1]);
        else if (splitCommand[0].equals("send"))
            sendFile(splitCommand[1]);
        
        cb.clear();
        buffIndex = 0;
        
     
    }
}//GEN-LAST:event_cmdTextAreaKeyPressed
private void cmdTextAreaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cmdTextAreaFocusGained
// TODO add your handling code here:
}//GEN-LAST:event_cmdTextAreaFocusGained

private void cmdTextAreaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cmdTextAreaFocusLost
// TODO add your handling code here:
}//GEN-LAST:event_cmdTextAreaFocusLost

private void cmdTextAreaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cmdTextAreaKeyTyped
   
   
}//GEN-LAST:event_cmdTextAreaKeyTyped

private void downloadBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_downloadBtnActionPerformed
    
}//GEN-LAST:event_downloadBtnActionPerformed

private void downloadBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_downloadBtnMouseClicked
    this.getFile(this.fileList.getSelectedItem());
}//GEN-LAST:event_downloadBtnMouseClicked

private void uploadBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_uploadBtnMouseClicked
    final JFileChooser fc = new JFileChooser();
    int returnVal = fc.showOpenDialog(NoteBoardClientGUI.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            String file2SendPath = fc.getSelectedFile().getPath();
            this.sendFile(file2SendPath);  
            this.doLs();
        }
}//GEN-LAST:event_uploadBtnMouseClicked

private void fileListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileListMouseClicked
    if (evt.getClickCount() == 2)
    {
        this.doCd(this.fileList.getSelectedItem());
        this.doLs();
    }
}//GEN-LAST:event_fileListMouseClicked

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
            
                
                new NoteBoardClientGUI().setVisible(true);
                
                
                
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea cmdTextArea;
    private javax.swing.JButton downloadBtn;
    private java.awt.List fileList;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton uploadBtn;
    // End of variables declaration//GEN-END:variables



}
